package tgc.rj.zz.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import tgc.rj.zz.service.SysUserService;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{

	@Autowired
	private SysUserService userService;
	
	/*
	 * 用户认证方法
	 */
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth
			.userDetailsService(userService)
			.passwordEncoder(new BCryptPasswordEncoder());
		auth
			.inMemoryAuthentication().withUser("root").password("{noop}root").roles("SYSTEM","DBA");
	}
	
	/*
	 * 用户授权方法
	 */
	@Override
	protected void configure(HttpSecurity http) throws Exception {
	 	http.csrf().disable();
	 	http.headers().frameOptions().disable();
	 	http.formLogin()
			.loginPage("/login").permitAll()
			.defaultSuccessUrl("/main")
            .failureUrl("/login?error");
	 	http.logout().logoutUrl("/logout").permitAll();
        http.authorizeRequests().antMatchers("/static/**").permitAll();
        http.authorizeRequests().antMatchers("/webjars/**").permitAll();
        http.authorizeRequests().anyRequest().authenticated();
	/*	http.authorizeRequests()
		.antMatchers("/login").permitAll()
		.antMatchers("/main/**").hasAnyRole("ADMIN","SYSTEM","DBA")
		.and()
			.formLogin()
			.loginPage("/login").permitAll()
			.defaultSuccessUrl("/main")
			.failureUrl("/login?error"); */  
			
	}
	
	
}
